package com.example.martian.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.martian.config.util.RedisUtils;
import com.example.martian.service.RegisterService;
import com.example.martian.utils.SmsMessage;
import com.example.martian.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/register/")
@CrossOrigin
public class RegisterCrotroller {
    @Autowired
    private RegisterService registerService;

    private static final long EXPIRE_DATE = 30 * 60 * 100000;
    //token秘钥
    private static final String TOKEN_SECRET = "ZCEQIUBFKSJBFJH2020BQWE";

    @Autowired
    private RedisUtils redisUtils;

    //注册
    @ResponseBody
    @RequestMapping(value = "registerPhoneOrEmail")
    public Object registerPhoneOrEmail(String address, String password,String passwordrep,String invitationcode,String code) throws Exception {
        return registerService.registerPhoneOrEmail(address, password,passwordrep,invitationcode, code);
    }

    //登录
    @ResponseBody
    @RequestMapping(value = "login")
    public Object login(String address, String password, HttpServletResponse response, HttpServletRequest request) {
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("address", address)
                    .withClaim("password", password).withExpiresAt(date)
                    .sign(algorithm);
            response.setHeader("Authorization", token);
            request.getSession().setAttribute("Authorization", token);
            request.getSession().setMaxInactiveInterval(240 * 60);
            request.getSession().removeAttribute(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str = registerService.login(address, password,token).toString();
        return Utils.toJSON(str, token);
    }

    //查询账户余额
    @ResponseBody
    @RequestMapping(value = "selectAllCoinMoney")
    public Object selectAllCoinMoney(String address) {
        return registerService.selectAllCoinMoney(address);
    }


    //快速登录
    @ResponseBody
    @RequestMapping(value = "celerityLogin")
    public Object celerityLogin(String address, String code, HttpServletResponse response, HttpServletRequest request) {
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("address", address)
                    .withClaim("password", code).withExpiresAt(date)
                    .sign(algorithm);
            response.setHeader("Authorization", token);
            request.getSession().setAttribute("Authorization", token);
            request.getSession().setMaxInactiveInterval(240 * 60);
            request.getSession().removeAttribute(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str = registerService.celerityLogin(address,code).toString();
        return Utils.toJSON(str, token);
    }

    //找回密码
    @ResponseBody
    @RequestMapping(value = "forgetPass")
    public Object forgetPass(String address,String password,String passwordrep) {
        return registerService.forgetPass(address, password, passwordrep);
    }

    //修改登录密码
    @ResponseBody
    @RequestMapping(value = "updatePassword")
    public Object updatePassword(Integer userId, String oldpassword, String password, String passwordrep) {
        return registerService.updateLoginPassword(userId, oldpassword, password, passwordrep);
    }

    /**
     * 设置昵称或者头像
     */
    @ResponseBody
    @RequestMapping(value = "updatenickname", produces = "application/json;charset=UTF-8")
    public Object updatenickname(MultipartFile img, String nickname, String userid) {
        return registerService.updateNickName(img, nickname,userid);
    }

    //设置交易密码
    @ResponseBody
    @RequestMapping(value = "addJYpassword")
    public Object addJYpassword(Integer userid, String jypassword, String jypasswordrep,String code) {
        return registerService.addJYpassword(userid, jypassword, jypasswordrep,code);
    }
    //发送验证码
    @ResponseBody
    @RequestMapping(value = "sendSmsSendMessage")
    public Object sendSmsSendMessage(String address) {
        return registerService.sendSmsSendMessage(address);
    }

    //退出登录
    @ResponseBody
    @RequestMapping(value = "exitLogin")
    public Object exitLogin(String token, HttpServletRequest request) {
        HttpSession session = request.getSession();
        System.out.println(session);
        request.removeAttribute(token);
        return Utils.toJSON("退出成功",Utils.toJSONmap(),"0");
    }

    //邀请页面
    @ResponseBody
    @RequestMapping(value = "invitation")
    public Object invitation(Integer userId) {
        return registerService.invitation(userId);
    }

    //查询头像
    @ResponseBody
    @RequestMapping(value = "selectNikeNameAndPhoto")
    public Object selectNikeNameAndPhoto(Integer userId) {
        return registerService.selectNikeNameAndPhoto(userId);
    }

    /**
     * APP更新信息
     */
    @ResponseBody
    @RequestMapping(value = "appUpdateInfomation", produces = "application/json;charset=UTF-8")
    public Object appUpdateInfomation() {
        return registerService.appUpdateInfomation();
    }

    @ResponseBody
    @RequestMapping(value = "checkJymimaZt", produces = "application/json;charset=UTF-8")
    public Object checkJymimaZt(Integer userId) {
        return registerService.checkJymimaZt(userId);
    }

    @ResponseBody
    @RequestMapping(value = "selectNewAward", produces = "application/json;charset=UTF-8")
    public Object selectNewAward(Integer userId) {
        return registerService.selectNewAward(userId);
    }


    //校验验证码
    @ResponseBody
    @RequestMapping(value = "verificationMessage", produces = "application/json;charset=UTF-8")
    public Object verificationMessage(String code,String address) {
        Boolean aBoolean = registerService.verificationMessage(code, address);
        if (!aBoolean){
            return Utils.toJSON("验证码输入错误",Utils.toJSONmap(),"1");
        }
        return Utils.toJSON("验证码正确",Utils.toJSONmap(),"0");
    }
}
